package com.fxz.security;

import cn.hutool.core.util.StrUtil;
import com.fxz.entity.SysUser;
import com.fxz.service.SysUserService;
import com.fxz.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义JWT认证过滤器
 * @author fxz
 * @date 2021/5/7
 **/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserDetailServiceImpl userDetailsService;
    @Autowired
    SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取请求头里面的jwt
        String jwt = request.getHeader(jwtUtils.getHeader());
        //jwt为空 过滤器链接着往后走

        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        Claims claim = jwtUtils.getClaimByToken(jwt);
        if(claim==null){
            throw new JwtException("token异常!");
        }
        if(jwtUtils.isTokenExpired(claim)){
            throw new JwtException("token已经过期");
        }

        String username = claim.getSubject();
        //获取用户的权限信息

        SysUser user = sysUserService.getByUserName(username);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, userDetailsService.getUserAuthority(user.getId()));
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request,response);

    }
}
